﻿using System.Text;

using Cognifide.PowerShell.Shell.Host;
using Cognifide.PowerShell.Shell.Settings;

using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using System;
using Cognifide.PowerShell.Shell;

using System.Web;

namespace Cognifide.PowerShell.Console.Layouts
{
    public class PowerShellResultsXml : global::Sitecore.Web.UI.Sheer.BaseForm
    {
        Literal txtResult=null;

        private string itemId;
        private string scriptId;
        private string databaseId;

        public const string VERSION_STRING = "Sitecore Powershell Console\r\n<br/>Copyright (c) 2010-2011 <a href='http://www.cognifide.com' target='_blank'>Cognifide Limited</a> & <a href='http://blog.najmanowicz.com/' target='_blank'>Adam Najmanowicz</a>.<br/> All rights Reserved<br/><br/>";
        private PsConsoleSettings Settings { get { return PsConsoleSettings.Instance; } }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            itemId = Context.Request.GetQueryString("id");
            scriptId = Context.Request.GetQueryString("script");
            databaseId = Context.Request.GetQueryString("sc_content");
            if(String.IsNullOrEmpty(databaseId))
            {
                databaseId = "master";
            }
            txtResult.Text = VERSION_STRING;

            Item item = Factory.GetDatabase(databaseId).GetItem(new ID(itemId));
            Item scriptItem = Factory.GetDatabase("core").GetItem(new ID(scriptId));

            using (var scriptSession = new ScriptSession())
            {
                try
                {
                    scriptSession.ExecuteScriptPart("Set-HostProperty -HostWidth 80");
                    scriptSession.ExecuteScriptPart(PsConsoleSettings.Instance.PreScript);
                    scriptSession.ExecuteScriptPart(String.Format("cd \"{0}:{1}\"", item.Database.Name,item.Paths.Path.Replace("/","\\").Substring(9)));
                    scriptSession.ExecuteScriptPart(scriptItem["Script"]);
                }
                catch (Exception exc)
                {
                    txtResult.Text += "<span style='background-color:black;color:red;'>" + scriptSession.GetExceptionString(exc).Replace("\r\n", "<br/>").Replace(" ", "&nbsp;") + "</span>";
                }

                StringBuilder output = new StringBuilder(10240);
                foreach (var outputLine in scriptSession.Output)
                {
                    outputLine.GetHtmlLine(output);
                    output.Append("<br/>");
                }
                output.Replace(" ", "&nbsp;");
                txtResult.Text += output.ToString();
            }

        }

    }
}
